const methods = {}

methods.save = (Model, data) => {
  return new Promise((resolve, reject) => {
    const model = new Model(data)
    model.save((err, res) => {
      if(err) reject(err)
      else resolve(res)
    })
  })
}

methods.query = (Model, conditions) => {
  return new Promise((resolve, reject) => {
    Model.find(conditions, (err, res) => {
      if(err) reject(err)
      else resolve(res)
    })
  })
}

methods.getAll = (Model) => {
  return new Promise((resolve, reject) => {
    Model.find((err, res) => {
      if(err) reject(err)
      else resolve(res)
    })
  })
}

methods.getOne = (Model, conditions) => {
  return new Promise((resolve, reject) => {
    Model.where(conditions).findOne((err, res) => {
      if(err) reject(err)
      else resolve(res)
    })
  })
}

methods.getCount = (Model, conditions) => {
  return new Promise((resolve, reject) => {
    Model.find(conditions).count((err, res) => {
      if(err) reject(err)
      else resolve(res)
    })
  })
}

methods.update = (Model, condition, value) => {
  return new Promise((resolve, reject) => {
    Model.where(condition).update(value, (err, res) => {
      if(err) reject(err)
      else resolve()
    })
  })
}

methods.select = (Model, conditions, selectedItems) => {
  return new Promise((resolve, reject) => {
    Model.find(conditions).select(selectedItems).exec((err, res) => {
      if(err) reject(err)
      else resolve(res)
    })
  })
}

methods.remove = (Model, condition) => {
  return new Promise((resolve, reject) => {
    Model.where(condition).remove((err, res) => {
      if(err) reject(err)
      else resolve()
    })
  })
}

// 这里以后想想换Typescript后要如何写，接受参数为函数或是函数数组
methods.promiseWrapper = (fnArr) => {
  const singleWrapper = (fn) => {
    return new Promise((resolve, reject) => {
      fn((err, res) => {
        if(err) reject()
        else resolve(res)
      })
    })
  }
  if(typeof fnArr === 'function')
    return singleWrapper(fnArr)
  else if(Array.isArray(fnArr))
    return Promise.all(fnArr.map(singleWrapper))
}

module.exports = methods